package com.xd.core.system.entity;

import com.alibaba.fastjson.annotation.JSONField;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.xd.core.company.entity.Company;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "登录用户信息")
public class LoginUser implements UserDetails {
    @ApiModelProperty(value = "用户信息")
    private SysUser user;
    @ApiModelProperty(value = "用户角色")
    private SysRole role;
    private List<String> permissions;
    @ApiModelProperty(value = "用户权限信息")
    private List<SysPermission> sysPermission;//前端使用展示菜单使用
    @ApiModelProperty(value = "企业信息")
    private Company company;
    @ApiModelProperty(value = "部门ID")
    private Integer groupId;


    public LoginUser(SysUser user, List<String> permissions, List<SysPermission> sysPermission, SysRole role,Company company,Integer groupId) {
        this.role = role;
        this.user = user;
        this.company = company;
        this.permissions = permissions;
        this.sysPermission = sysPermission;
        this.groupId = groupId;
    }

    //权限集合
    @JSONField(serialize = false)
    private List<SimpleGrantedAuthority> authorities;


    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        //获取权限信息
        if (authorities != null) {
            return authorities;
        }
        //把permissions中String类型的权限信息封装成SimpleGrantedAuthority
        //第一种方式
//         List<GrantedAuthority> newList = new ArrayList<>();
//        for (String permission : permissions) {
//            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
//            newList.add(authority);
//        }
        //方式二

        authorities = permissions.stream().
                map(SimpleGrantedAuthority::new).
                collect(Collectors.toList());

        return authorities;
    }

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getUserName();
    }

    //是否未过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //是否未锁定
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //凭证是否未过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //是否可用
    @Override
    public boolean isEnabled() {
        return true;
    }
}
